//
//  GameScene.swift
//  mng
//
//  Created by WTFKL on 2018/3/26.
//  Copyright © 2018年 WTF. All rights reserved.
//

import SpriteKit
import GameplayKit


enum m_direction {
    case left
    case right
    case stop
    case jump
}


class GameScene: SKScene , SKPhysicsContactDelegate{
     var ground : SKSpriteNode?;
     var myState = m_direction.stop;
     var isOnGround = true;
     var walllf : SKSpriteNode?;
     var wallrt : SKSpriteNode?;
     var doorWall : SKSpriteNode?;
    //角色
     var mesprite : MeCharactor?;
    //提示
     var tips : SKLabelNode?;
    //射线
     var line : SKSpriteNode?;
    //屏幕尺寸
     var screenWidth : CGFloat = UIScreen.main.bounds.size.width;
     var screenHeight : CGFloat = UIScreen.main.bounds.size.height;
    //hud
     var leftBtn : SKSpriteNode?;
     var rightBtn : SKSpriteNode?;
     var jumpButton:SKSpriteNode?;
     var phoneType:Bool?;
    override func didMove(to view: SKView) {
        phoneType = screenWidth<736;
        initWorldNodes();
        initHUD();
    }
    
    func initHUD(){
        leftBtn = SKSpriteNode(texture: SKTexture(image: #imageLiteral(resourceName: "arrow2")));
        leftBtn?.name = "left";
        leftBtn?.size = CGSize(width: (ground?.size.height)!, height: (ground?.size.height)!);
        leftBtn?.position = CGPoint(x: -screenWidth/2+(leftBtn?.size.width)!, y: (ground?.position.y)!);
        self.addChild(leftBtn!);
        rightBtn = SKSpriteNode(texture: SKTexture(image: #imageLiteral(resourceName: "arrow")));
        rightBtn?.name = "right";
        rightBtn?.size = CGSize(width: (ground?.size.height)!, height: (ground?.size.height)!);
        rightBtn?.position = CGPoint(x: (leftBtn?.position.x)! + (rightBtn?.size.width)! + 10, y: (ground?.position.y)!);
        self.addChild(rightBtn!);
        jumpButton = SKSpriteNode(color: .red, size: CGSize(width: 80, height: 80));
        jumpButton?.name = "Jump";
        jumpButton?.position = CGPoint(x: screenWidth/2-(jumpButton?.size.width)! + 10, y: (ground?.position.y)!);
        self.addChild(jumpButton!);
    }
    
    
    func initWorldNodes(){
        
        tips = SKLabelNode(text: "tips");
        tips?.position = CGPoint(x: 0, y: 30);
        tips?.fontSize = 24;
        tips?.fontColor = UIColor.black;
        tips?.fontName = "GB18030 Bitmap";
        self.addChild(tips!);
        
        let scaleAc = SKAction.scale(to: 0.5, duration: 1);
        let waitAc = SKAction.wait(forDuration: 2);
        let moveAc = SKAction.move(to:CGPoint(x: -240, y: 160) , duration: 1);
        let que = SKAction.sequence([waitAc,scaleAc,moveAc]);
        tips?.run(que);
        physicsWorld.contactDelegate = self;
        self.physicsWorld.gravity = CGVector(dx: 0, dy: -9.8);
        
        //地面
        ground = SKSpriteNode(color: .black, size: CGSize(width: screenWidth, height:100));
        ground?.position = CGPoint(x: 0, y: (-screenHeight+(ground?.size.height)!)/2);
        ground?.physicsBody = SKPhysicsBody(rectangleOf: (ground?.frame.size)!);
        ground?.physicsBody?.affectedByGravity = false;
        ground?.physicsBody?.isDynamic = false;
        ground?.physicsBody?.restitution = 0;
        ground?.physicsBody?.categoryBitMask = BitMaskType.ground;
        ground?.physicsBody?.contactTestBitMask = BitMaskType.charactor;//能被角色碰撞
        ground?.zPosition = -1;
        self.addChild(ground!);
        
        
        //角色
        mesprite = MeCharactor(mName: "me", mSize: CGSize.init(width: 20, height: 50));
        mesprite?.position = CGPoint(x: -250, y: (ground?.position.y)!+(mesprite?.size.height)!);
        mesprite?.physicsBody?.usesPreciseCollisionDetection = true;
//        self.addChild(mesprite!);
        line = SKSpriteNode(color: .clear, size: CGSize(width: 1, height: 4));
        line?.position = CGPoint(x: (mesprite?.position.x)!, y: (mesprite?.position.y)!-(line?.size.height)!/2);
        line?.physicsBody = SKPhysicsBody(rectangleOf: (line?.size)!);
        line?.physicsBody?.collisionBitMask = BitMaskType.line;
        line?.physicsBody?.categoryBitMask = BitMaskType.line;
        line?.physicsBody?.contactTestBitMask = BitMaskType.ground | BitMaskType.SpecialGround | BitMaskType.board;
        line?.physicsBody?.restitution = 0;
        self.addChild(mesprite!);
        self.addChild(line!);
        //创建射线
        let physicsConnect = SKPhysicsJointFixed.joint(withBodyA: (mesprite?.physicsBody)!, bodyB: (line?.physicsBody)!, anchor: (mesprite?.position)!);
        self.physicsWorld.add(physicsConnect);

        
        
        walllf = SKSpriteNode(color: .black, size: CGSize(width: 20, height: screenHeight));
        walllf?.position = CGPoint(x: (-screenWidth+(walllf?.size.width)!)/2, y: 0);
        walllf?.physicsBody = SKPhysicsBody(rectangleOf: (walllf?.frame.size)!);
        walllf?.physicsBody?.affectedByGravity = false;
        walllf?.physicsBody?.isDynamic = false;
        walllf?.physicsBody?.categoryBitMask = BitMaskType.wall;
        walllf?.physicsBody?.collisionBitMask = BitMaskType.charactor;
        walllf?.physicsBody?.contactTestBitMask = BitMaskType.charactor;//能被角色碰撞
        self.addChild(walllf!);
        
        
        doorWall = SKSpriteNode(color: .black, size: CGSize(width: 10, height: (mesprite?.size.height)!+10));
        doorWall?.position = CGPoint(x: screenWidth/2 - (doorWall?.size.width)!-10, y:((ground?.position.y)!+(ground?.size.height)!/2)+(doorWall?.size.height)!/2);
        doorWall?.physicsBody = SKPhysicsBody(rectangleOf: (doorWall?.frame.size)!);
        doorWall?.physicsBody?.affectedByGravity = false;
        doorWall?.physicsBody?.isDynamic = false;
        doorWall?.physicsBody?.categoryBitMask = BitMaskType.doorWall;
        doorWall?.physicsBody?.collisionBitMask = BitMaskType.charactor;
        doorWall?.physicsBody?.contactTestBitMask = BitMaskType.charactor;
        self.addChild(doorWall!);
        

    
        wallrt = SKSpriteNode(color: .black, size: CGSize(width: 40, height: screenHeight - (doorWall?.position.y)!-(doorWall?.size.height)!/2));
        wallrt?.position = CGPoint(x: (screenWidth-(wallrt?.size.width)!)/2, y: screenHeight-(wallrt?.size.height)!/2);
        wallrt?.physicsBody = SKPhysicsBody(rectangleOf: (wallrt?.frame.size)!);
        wallrt?.physicsBody?.affectedByGravity = false;
        wallrt?.physicsBody?.isDynamic = false;
        wallrt?.physicsBody?.categoryBitMask = BitMaskType.wall;
        wallrt?.physicsBody?.collisionBitMask = BitMaskType.charactor;
        wallrt?.physicsBody?.contactTestBitMask = BitMaskType.charactor;//能被角色碰撞
        self.addChild(wallrt!);

        
        
        //通关触发器
        let success = SK_Trigger(mName: "success",
                                 mSize: CGSize.init(width: 19.3, height: 65.6),
                                 mColor: .clear, mPosition: CGPoint.init(x: 358.3, y: -74.1),
                                 mCollisonBitMask: BitMaskType.ground,
                                 mContactTestBitMask: BitMaskType.charactor);
        self.addChild(success);
        
    }
    
    // MARK: - 触摸事件
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for t in touches {
            let location = t.location(in: self);
            
            let mnode = nodes(at: location);
            
            for nnode in mnode{
                let na = nnode as? SKSpriteNode;
                if(na?.name == "left"){
                    myState = m_direction.left;
                    mesprite?.texture = SKTexture(image: #imageLiteral(resourceName: "charactor2"));
                }
                if(na?.name == "right"){
                    myState = m_direction.right;
                    mesprite?.texture = SKTexture(image: #imageLiteral(resourceName: "charactor"));
                }
                if(na?.name == "Jump"){
                    if isOnGround{
                        mesprite?.physicsBody?.velocity = CGVector(dx: 0, dy: 0);
                        mesprite?.physicsBody?.applyImpulse(CGVector.init(dx: 0, dy: (mesprite?.jumpHeight)!));
                        isOnGround = false;
                    }
                }
            }
        }
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        for t in touches {
            let location = t.location(in: self);
            
            let mnode = nodes(at: location);
            
            for nnode in mnode{
                let na = nnode as? SKSpriteNode;
                if(na?.name == "left"||na?.name == "right"){
                    myState = m_direction.stop;
                }
            }
        }
    }

    //碰撞检测
    func didBegin(_ contact: SKPhysicsContact) {

        if (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask) == (BitMaskType.charactor | BitMaskType.doorWall) {//人物与门
            if(mesprite?.isGetKey == true){
                doorWall?.removeFromParent();
                let door = SKSpriteNode(texture: SKTexture(image: #imageLiteral(resourceName: "door")));
                door.size = CGSize(width: 50, height: (doorWall?.size.height)!)
                door.position = CGPoint(x: (doorWall?.position.x)!-(door.size.width)/2, y: (doorWall?.position.y)!);
                self.addChild(door);
            }
        }
        
        if((contact.bodyA.categoryBitMask|contact.bodyB.categoryBitMask) == (BitMaskType.line | BitMaskType.ground)){//检测角色否在地面
           isOnGround = true
            
        }
        if((contact.bodyA.categoryBitMask|contact.bodyB.categoryBitMask) == (BitMaskType.line | BitMaskType.board)){//检测角色否在隔板
            isOnGround = true
        }
        
      
    }
    
    
    override func update(_ currentTime: TimeInterval) {
//        line?.position = CGPoint(x: mesprite!.position.x, y: (mesprite?.position.y)!-(line?.size.height)!/2);
        switch myState {
        case .left:
            mesprite?.position.x += -3;
        case .right:
            mesprite?.position.x += 3;
        default:
            break;
        }
    }
    
}
